package com.anhuanjia.tools.eao.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.IOUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.anhuanjia.tools.eao.bean.EaoDatabaseFile;
import com.anhuanjia.tools.eao.bean.EaoImages;
import com.anhuanjia.tools.eao.bean.EaoProjectDoc;
import com.anhuanjia.tools.eao.bean.EaoPublicityEnclosure;
import com.anhuanjia.tools.eao.config.FileUploadFileDirConfig;
import com.anhuanjia.tools.eao.config.FileUploadOssDocConfig;
import com.anhuanjia.tools.eao.config.FileUploadPreviewPathConfig;
import com.efastsoft.aliyun.bl.AliyunOSSBL;
import com.efastsoft.aliyun.oss.item.OSSBucket;
import com.efastsoft.bean.CrmCertification;
import com.efastsoft.crm.CrmPlugin;
import com.efastsoft.framework.Config;
import com.efastsoft.framework.Member;
import com.efastsoft.framework.UIFacade;
import com.efastsoft.framework.annotation.Alias;
import com.efastsoft.framework.annotation.Priv;
import com.efastsoft.framework.annotation.Priv.LoginType;
import com.efastsoft.framework.collection.Mapx;
import com.efastsoft.framework.core.handler.EAction;
import com.efastsoft.framework.data.DataRow;
import com.efastsoft.framework.data.DataTable;
import com.efastsoft.framework.data.Q;
import com.efastsoft.framework.data.Transaction;
import com.efastsoft.framework.i18n.Lang;
import com.efastsoft.framework.thirdparty.commons.fileupload.FileItem;
import com.efastsoft.framework.ui.control.UploadAction;
import com.efastsoft.framework.utility.FileUtil;
import com.efastsoft.framework.utility.IOUtil;
import com.efastsoft.framework.utility.LogUtil;
import com.efastsoft.framework.utility.StringUtil;
import com.efastsoft.platform.util.NoUtil;

@Alias(value = "fileUpload")
public class FileUploadUI extends UIFacade {

	protected String PreviewPath = FileUploadPreviewPathConfig.getValue();
	private static final String OSS_DOC = FileUploadOssDocConfig.getValue();
	private static final String FILE_DIR = FileUploadFileDirConfig.getValue();
	/****************************************
	 * 项目流程上传
	 *******************************************/
	/**
	 * 项目流程上传
	 * 
	 * @param ua
	 */
	@Priv(loginType = LoginType.Member)
	public void uploadAvatar(UploadAction ua) {
		
		try {
			String key = $V("Key");
			String id = $V("Id");
			String name = $V("Name");
			if (StringUtils.isEmpty(name)) {
				name = UUID.randomUUID().toString().toLowerCase().substring(0, 5);
			} else {
				name = UUID.randomUUID().toString().toLowerCase().substring(0, 5) + name;
			}
			int year = LocalDate.now().getYear();
			int month = LocalDate.now().getMonthValue();
			String baseUrl = OSS_DOC + FILE_DIR + "/" + year + "-" + month + "/";
			FileUtil.mkdir(baseUrl);

			List<FileItem> fileItemList = ua.getAllFiles();
			if (!CollectionUtils.isEmpty(fileItemList)) {
				for (FileItem fi : fileItemList) {
					String fileName = fi.getName();
					String newFileName = name + fileName;
					String filePath = FILE_DIR + "/" + year + "-" + month + "/" + newFileName;
					File file = new File(baseUrl + newFileName);
					fi.write(file);
					String resource_url = AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, filePath,
							3600L * 24 * 365 * 1000);
					Mapx<String, String> map = new Mapx<>();
					map.put(key, resource_url);
					FileUploadUI.projectDoc(map, id);
				}
			}
			s(Lang.get("Common.ExecuteSuccess"));
		} catch (Exception ex) {
			f(Lang.get("Common.ExecuteFailed"));
			ex.printStackTrace();
		}

	}

	// 路径保存数据库
	public static void projectDoc(Mapx<String, String> map, String id) {
		Transaction transaction = new Transaction();
		DataTable dt = new Q("select *  from eao_project_doc where ProjectId=?", id).fetch();
		if (dt.getRowCount() != 0) {
			EaoProjectDoc projectDocUpdate = new EaoProjectDoc();
			projectDocUpdate.setValue(dt.get(0));
			projectDocUpdate.setValue(map);
			transaction.update(projectDocUpdate);
			transaction.commit();
		}
	}

	/****************************************
	 * 审核流程上传
	 *******************************************/
	/**
	 * 审核流程上传
	 * 
	 * @param ua
	 */
	@Priv(loginType = LoginType.Member)
	public void uploadAudit(UploadAction ua) {

		try {
			String key = $V("Key");
			String id = $V("Id");
			String name = $V("Name");
			String type = name.substring(0, 2);
			int year = LocalDate.now().getYear();
			int month = LocalDate.now().getMonthValue();
			String baseUrl = OSS_DOC + FILE_DIR + "/" + year + "-" + month + "/";
			FileUtil.mkdir(baseUrl);
			List<FileItem> fileItemList = ua.getAllFiles();
			if (!CollectionUtils.isEmpty(fileItemList)) {
				for (FileItem fi : fileItemList) {
					String fileName = fi.getName();
					String newFileName = UUID.randomUUID().toString().toLowerCase().substring(0, 5) + name + fileName;
					String filePath = FILE_DIR + "/" + year + "-" + month + "/" + newFileName;
					File file = new File(baseUrl + newFileName);
					fi.write(file);
					String resource_url = AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, filePath,
							3600L * 24 * 365 * 1000);
					Mapx<String, String> map = new Mapx<>();
					map.put(key, resource_url);
					FileUploadUI.auditFile(map, id, type);
				}
			}
			s(Lang.get("Common.ExecuteSuccess"));
		} catch (Exception ex) {
			f(Lang.get("Common.ExecuteFailed"));
			ex.printStackTrace();
		}

	}

	// 路径保存数据库
	public static void auditFile(Mapx<String, String> map, String id, String name) {
		Transaction transaction = new Transaction();
		EaoImages entity = new EaoImages();
		DataTable dataTable = new DataTable();
		if ("一审".equals(name)) {
			dataTable = new Q(" select * from eao_images where ParentId = ? and Status = ?", id, name).fetch();
		} else if ("二审".equals(name)) {
			dataTable = new Q(" select * from eao_images where ParentId = ? and Status = ?", id, name).fetch();
		} else if ("初审".equals(name)) {
			dataTable = new Q(" select * from eao_images where ParentId = ? and Status = ?", id, name).fetch();
		} else if ("复审".equals(name)) {
			dataTable = new Q(" select * from eao_images where ParentId = ? and Status = ?", id, name).fetch();
		} else if ("终审".equals(name)) {
			dataTable = new Q(" select * from eao_images where ParentId = ? and Status = ?", id, name).fetch();
		}
		DataTable dataTable1 = new Q(" select * from eao_project_doc where ProjectId = ? ", id).fetch();
		if (dataTable.getRowCount() != 0) {
			entity.setValue(dataTable.get(0));
			entity.setValue(map);
			entity.setUpdateTime(new Date());
			transaction.update(entity);
			// 保存上次上传
			if (dataTable1.getRowCount() != 0) {
				EaoProjectDoc doc = new EaoProjectDoc();
				doc.setValue(dataTable1.get(0));
				doc.setProjectEnvOverview(dataTable.getString(0, "ImgUrl"));
				transaction.update(doc);
			}
		} else {
			entity.setId(UUID.randomUUID().toString());
			entity.setParentId(id);
			entity.setStatus(name);
			entity.setValue(map);
			entity.setOperator(Member.getRealName());
			entity.setCreateTime(new Date());
			entity.setUpdateTime(new Date());
			transaction.insert(entity);
		}
		transaction.commit();
	}

	/*******************************************
	 * 数据库文件上传
	 ***************************************************/
	/**
	 * @功能 上传素材接口
	 * @param siteRoot 文件将要保存的目录
	 * @return
	 */
	@Priv(loginType = LoginType.Member)
	public void saveUrlAs(UploadAction ua) {
		try {
			String key = $V("Key");
			String id = $V("Id");
			int year = LocalDate.now().getYear();
			int month = LocalDate.now().getMonthValue();
			String baseUrl = OSS_DOC + FILE_DIR + "/" + year + "-" + month + "/";
			FileUtil.mkdir(baseUrl);

			List<FileItem> fileItemList = ua.getAllFiles();
			if (!CollectionUtils.isEmpty(fileItemList)) {
				for (FileItem fi : fileItemList) {
					String fileName = fi.getName();
					String newFileName = UUID.randomUUID().toString().toLowerCase().substring(0, 5) + fileName;
					String filePath = FILE_DIR + "/" + year + "-" + month + "/" + newFileName;
					File file = new File(baseUrl + newFileName);
					fi.write(file);
					String resource_url = AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, filePath,
							3600L * 24 * 365 * 1000);
					Mapx<String, String> map = new Mapx<>();
					map.put(key, resource_url);
//					map.put(key, filePath.replaceAll("\\\\", "/"));
					FileUploadUI.databaseFile(map, fileName, id);
				}
			}
			s(Lang.get("Common.ExecuteSuccess"));
		} catch (Exception ex) {
			f(Lang.get("Common.ExecuteFailed"));
			ex.printStackTrace();
		}
	}

	public static void databaseFile(Mapx<String, String> map, String name, String id) {
		Transaction transaction = new Transaction();
		EaoDatabaseFile databaseFile = new EaoDatabaseFile();
		if (StringUtils.isEmpty(id)) {
			databaseFile.setId(UUID.randomUUID().toString());
			databaseFile.setName(name);
			databaseFile.setValue(map);
			transaction.insert(databaseFile);
		} else {
			DataTable dataTable = new Q(" select * from eao_database_file where Id = ? ", id).fetch();
			databaseFile.setValue(dataTable.get(0));
			databaseFile.setName(name);
			databaseFile.setValue(map);
			transaction.update(databaseFile);
		}
		transaction.commit();
	}

//	public static void main(String[] args) {
//		String photoUrl = "http://192.168.0.198:8080/eao/misc/tmp/c5c857e48ff64121aaa344bd8377cd31.png";
//		String fileName = photoUrl.substring(photoUrl.lastIndexOf("/"));
//		// System.out.println("fileName---->"+fileName);
//		String filePath = "d:";
//		FileUploadUI fileUploadUI = new FileUploadUI();
////		fileUploadUI.saveUrlAs(photoUrl, filePath + fileName);
//		System.out.println("Run ok!/n<BR>Get URL file " + photoUrl + filePath + fileName);
//	}

	/*************************************
	 * 公示附件上传
	 **************************************************/
	/**
	 * 公示附件上传
	 * 
	 * @param ua
	 */
	@Priv(loginType = LoginType.Member)
	public void uploadAvatar2(UploadAction ua) {
		try {
			String key = $V("Key");
			String id = $V("Id");
			int year = LocalDate.now().getYear();
			int month = LocalDate.now().getMonthValue();
			String baseUrl = OSS_DOC + FILE_DIR + "/" + year + "-" + month + "/";
			FileUtil.mkdir(baseUrl);

			List<FileItem> fileItemList = ua.getAllFiles();
			if (!CollectionUtils.isEmpty(fileItemList)) {
				for (FileItem fi : fileItemList) {
					String fileName = fi.getName();
					String newFileName = UUID.randomUUID().toString().toLowerCase().substring(0, 5) + fileName;
					String filePath = FILE_DIR + "/" + year + "-" + month + "/" + newFileName;
					File file = new File(baseUrl + newFileName);
					fi.write(file);
					String resource_url = AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, filePath,
							3600L * 24 * 365 * 1000);
					Mapx<String, String> map = new Mapx<>();
					map.put(key, resource_url);
					FileUploadUI.publicityEnclosure(map, id);
				}
			}
			s(Lang.get("Common.ExecuteSuccess"));
		} catch (Exception ex) {
			f(Lang.get("Common.ExecuteFailed"));
			ex.printStackTrace();
		}
	}

	// 路径保存数据库
	public static void publicityEnclosure(Mapx<String, String> map, String id) {
		Transaction transaction = new Transaction();
		EaoPublicityEnclosure publicityEnclosure = new EaoPublicityEnclosure();
		publicityEnclosure.setId(UUID.randomUUID().toString());
		publicityEnclosure.setPublicityId(id);
		publicityEnclosure.setValue(map);
		transaction.insert(publicityEnclosure);
		transaction.commit();
	}

	/*******************************************
	 * 图片表上传
	 ***************************************************/
	/**
	 * @功能 上传图片接口
	 * @param siteRoot 文件将要保存的目录
	 * @return
	 */
	@Priv(loginType = LoginType.Member)
	public void saveUrlAs2(UploadAction ua) {
		try {
			String key = $V("Key");
			String id = $V("Id");
			int year = LocalDate.now().getYear();
			int month = LocalDate.now().getMonthValue();
			String baseUrl = OSS_DOC + FILE_DIR + "/" + year + "-" + month + "/";
			FileUtil.mkdir(baseUrl);

			List<FileItem> fileItemList = ua.getAllFiles();
			if (!CollectionUtils.isEmpty(fileItemList)) {
				for (FileItem fi : fileItemList) {
					String fileName = fi.getName();
					String newFileName = UUID.randomUUID().toString().toLowerCase().substring(0, 5) + fileName;
					String filePath = FILE_DIR + "/" + year + "-" + month + "/" + newFileName;
					File file = new File(baseUrl + newFileName);
					fi.write(file);
					String resource_url = AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, filePath,
							3600L * 24 * 365 * 1000);
					Mapx<String, String> map = new Mapx<>();
					map.put(key, resource_url);
					FileUploadUI.images(map, id);
				}
			}
			s(Lang.get("Common.ExecuteSuccess"));
		} catch (Exception ex) {
			f(Lang.get("Common.ExecuteFailed"));
			ex.printStackTrace();
		}
	}

	@Priv(loginType = LoginType.ALL)
	public void saveUrlAsAdmin(UploadAction ua) {
		try {
			LogUtil.warn("OSS_DOC"+OSS_DOC);
			LogUtil.warn("FILE_DIR"+FILE_DIR);
			String key = $V("Key");
			String id = $V("Id");
			int year = LocalDate.now().getYear();
			int month = LocalDate.now().getMonthValue();
			String baseUrl = OSS_DOC + FILE_DIR + "/" + year + "-" + month + "/";
			FileUtil.mkdir(baseUrl);

			List<FileItem> fileItemList = ua.getAllFiles();
			if (!CollectionUtils.isEmpty(fileItemList)) {
				for (FileItem fi : fileItemList) {
					String fileName = fi.getName();
					String newFileName = UUID.randomUUID().toString().toLowerCase().substring(0, 5) + fileName;
					String filePath = FILE_DIR + "/" + year + "-" + month + "/" + newFileName;
					File file = new File(baseUrl + newFileName);
					fi.write(file);
					String resource_url = AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, filePath,
							3600L * 24 * 365 * 1000);
					Mapx<String, String> map = new Mapx<>();
					map.put(key, resource_url);
					FileUploadUI.image(map, id);
				}
			}
			s(Lang.get("Common.ExecuteSuccess"));
		} catch (Exception ex) {
			f(Lang.get("Common.ExecuteFailed"));
			ex.printStackTrace();
		}
	}

	public static void images(Mapx<String, String> map, String id) {
		Transaction transaction = new Transaction();
		EaoImages entity = new EaoImages();
		entity.setId(UUID.randomUUID().toString());
		entity.setParentId(id);
		entity.setValue(map);
		entity.setOperator(Member.getRealName());
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		transaction.insert(entity);
		transaction.commit();
	}

	public static void image(Mapx<String, String> map, String id) {
		Transaction transaction = new Transaction();
		EaoImages entity = new EaoImages();
		entity.setId(UUID.randomUUID().toString());
		entity.setParentId(id);
		entity.setValue(map);
		entity.setOperator("");
		entity.setCreateTime(new Date());
		entity.setUpdateTime(new Date());
		transaction.insert(entity);
		transaction.commit();
	}

	/*******************************************
	 * 头像上传
	 ***************************************************/
	/**
	 * @功能 上传图片接口
	 * @param siteRoot 文件将要保存的目录
	 * @return
	 */
	@Priv(loginType = LoginType.Member)
	public void saveUrlPhoto(UploadAction ua) {
		try {
			String key = $V("Key");
			Long id = $L("Id");
			int year = LocalDate.now().getYear();
			int month = LocalDate.now().getMonthValue();
			String baseUrl = OSS_DOC + FILE_DIR + "/" + year + "-" + month + "/";
			FileUtil.mkdir(baseUrl);

			List<FileItem> fileItemList = ua.getAllFiles();
			if (!CollectionUtils.isEmpty(fileItemList)) {
				for (FileItem fi : fileItemList) {
					String fileName = fi.getName();
					String contentType = FileUtil.getExtension(fileName);
					String newFileName = UUID.randomUUID().toString().toLowerCase().substring(0, 5)
							+ Member.getRealName() + "." + contentType;
					String filePath = FILE_DIR + "/" + year + "-" + month + "/" + newFileName;
					File file = new File(baseUrl + newFileName);
					fi.write(file);
					String resource_url = AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, filePath,
							3600L * 24 * 365 * 1000);
					Mapx<String, String> map = new Mapx<>();
					map.put(key, resource_url);
					FileUploadUI.photo(map, Long.valueOf(id));
				}
			}
			s(Lang.get("Common.ExecuteSuccess"));
		} catch (Exception ex) {
			f(Lang.get("Common.ExecuteFailed"));
			ex.printStackTrace();
		}
	}

	public static void photo(Mapx<String, String> map, Long id) {
		Transaction transaction = new Transaction();
		EaoImages entity = new EaoImages();
		DataTable dataTable = new Q(" select * from eao_images where ParentId = ? and Status = '1'", id.toString())
				.fetch();
		if (dataTable.getRowCount() != 0) {
			entity.setValue(dataTable.get(0));
			entity.setValue(map);
			entity.setUpdateTime(new Date());
			transaction.update(entity);
		} else {
			entity.setId(UUID.randomUUID().toString());
			entity.setParentId(id.toString());
			entity.setValue(map);
			entity.setStatus("1");
			entity.setOperator(Member.getRealName());
			entity.setCreateTime(new Date());
			entity.setUpdateTime(new Date());
			transaction.insert(entity);
		}
		transaction.commit();
	}

	/*******************************************
	 * 机构证件扫描件上传
	 ***************************************************/
	/**
	 * @功能 机构证件扫描件接口
	 * @param siteRoot 文件将要保存的目录
	 * @return
	 */
	@Priv(loginType = LoginType.Member)
	public void saveUrlMechanism(UploadAction ua) {
		try {
			String key = $V("Key");
			Long id = $L("Id");
			String position = $V("Position");
			int year = LocalDate.now().getYear();
			int month = LocalDate.now().getMonthValue();
			String baseUrl = OSS_DOC + FILE_DIR + "/" + year + "-" + month + "/";
			FileUtil.mkdir(baseUrl);

			List<FileItem> fileItemList = ua.getAllFiles();
			if (!CollectionUtils.isEmpty(fileItemList)) {
				for (FileItem fi : fileItemList) {
					String fileName = fi.getName();
					String contentType = FileUtil.getExtension(fileName);
					String newFileName = UUID.randomUUID().toString().toLowerCase().substring(0, 5)
							+ Member.getRealName() + "." + contentType;
					String filePath = FILE_DIR + "/" + year + "-" + month + "/" + newFileName;
					File file = new File(baseUrl + newFileName);
					fi.write(file);
					String resource_url = AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, filePath,
							3600L * 24 * 365 * 1000);
					Mapx<String, String> map = new Mapx<>();
					map.put(key, resource_url);
					FileUploadUI.mechanism(map, Long.valueOf(id), position);
				}
			}
			s(Lang.get("Common.ExecuteSuccess"));
		} catch (Exception ex) {
			f(Lang.get("Common.ExecuteFailed"));
			ex.printStackTrace();
		}
	}

	public static void mechanism(Mapx<String, String> map, Long id, String position) {
		Transaction transaction = new Transaction();
		EaoImages entity = new EaoImages();
		DataTable dataTable = new DataTable();
		if ("3".equals(position)) {
			dataTable = new Q(" select * from eao_images where ParentId = ? and Status = ?", id.toString(), position)
					.fetch();
		} else if ("4".equals(position)) {
			dataTable = new Q(" select * from eao_images where ParentId = ? and Status = ?", id.toString(), position)
					.fetch();
		}
		if (dataTable.getRowCount() != 0) {
			entity.setValue(dataTable.get(0));
			entity.setValue(map);
			entity.setMemberId(String.valueOf(Member.getUID()));
			entity.setUpdateTime(new Date());
			transaction.update(entity);
		} else {
			entity.setId(UUID.randomUUID().toString());
			entity.setParentId(id.toString());
			entity.setStatus(position);
			entity.setValue(map);
			entity.setMemberId(String.valueOf(Member.getUID()));
			entity.setOperator(Member.getRealName());
			entity.setCreateTime(new Date());
			entity.setUpdateTime(new Date());
			transaction.insert(entity);
		}
		transaction.commit();
	}

	/**
	 * 下载
	 * 
	 * @param za
	 */
	@Priv(loginType = LoginType.Member)
	public void download(EAction za) {
		String url = $V("URL");
		String name = $V("Name");
		String[] URL = url.split(":/");
		String filePath = "//www/wwwroot" + URL[1];
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(filePath);
			IOUtil.download(za.getRequest(), za.getResponse(), name, fis);
		} catch (Exception e) {
			e.printStackTrace();
			za.writeHTML("File not found:" + filePath);
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return;
	}

	@Priv(loginType = LoginType.Member)
	public void download2(EAction za) {
		String name = $V("Name");
		String filePath = Config.getContextRealPath() + "eao/misc/tmp/" + name;
		FileInputStream fis = null;
		try {
			fis = new FileInputStream(filePath);
			IOUtil.download(za.getRequest(), za.getResponse(), name, fis);
		} catch (Exception e) {
			e.printStackTrace();
			za.writeHTML("File not found:" + filePath);
		} finally {
			try {
				if (fis != null) {
					fis.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return;
	}

	/**
	 * 下载
	 */
	@Priv(loginType = LoginType.Member)
	@Alias(value = "PcAttachment/download", url = true, alone = true)
	public void download1(EAction action) {
		String url = $V("URL");
		String name = $V("Name");
		if (StringUtils.isEmpty(name)) {
			String[] URL = url.split("/");
			name = URL[URL.length - 1];
		}
		InputStream is = null;
		try {
			String id = $V("Id");
			if (StringUtils.isEmpty(id)) {
				f("下载失败");
				return;
			} else {
				if (StringUtils.isEmpty(url)) {
					f("文件不存在");
					return;
				} else {
					if (File.separator.equals("\\")) {
						url = url.replaceAll("/", "\\\\");
					}
					is = new FileInputStream(new File(OSS_DOC + url));
					IOUtil.download(action.getRequest(), action.getResponse(), name, is);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			f("下载失败");
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	@Priv(loginType = LoginType.Member)
	@Alias(value = "mTemplate/download", url = true, alone = true)
	public void download7(EAction action) {
		InputStream is = null;
		try {
			String filePath = Config.getContextRealPath() + "/mhr/template/" + $V("File") + ".xlsx";
			is = new FileInputStream(new File(filePath));
			IOUtil.download(action.getRequest(), action.getResponse(), $V("FileName") + ".xlsx", is);
		} catch (Exception e) {
			e.printStackTrace();
			f("下载失败");
		} finally {
			IOUtils.closeQuietly(is);
		}
	}

	/**
	 * 机构资质扫描件上传
	 * 
	 * @param ua
	 */
	@Priv(loginType = LoginType.Member)
	public void upload(UploadAction ua) {

		long id = Member.getCompany();
		String identityType = $V("IdentityType"); // 类型
		int version = $I("Version");// 版本号
		String coverOrBack = $V("CoverOrBack");// 正面或反面
		if (ua == null) {
			f("请上传图片！");
			return;
		}
		FileItem fi = ua.getFirstFile();
		/**
		 * 上传的文件认证类型： "个人身份证件"；"01", "个人职称证书"；"02", "专家执业资质证书","03", "营业执照","04",
		 * "机构资质证书" 05
		 */
		if (StringUtil.isEmpty(coverOrBack)) {
			coverOrBack = "Cover";
		}
		if (StringUtil.isEmpty(String.valueOf(id)) || fi == null || StringUtil.isEmpty(identityType)
				|| StringUtil.isEmpty(version + "")) {
			f("信息不能为空");
			return;
		}
		/**
		 * 业务逻辑是：如果上传的版本号表里已存在，则执行更新操作；如果上传的版本号不存在 或者 为0，则执行新增操作
		 */
		CrmCertification certification = new CrmCertification();
		int lastVersion = new Q(
				"select MAX(Version) Version from crm_certification where BelongCustomerID=? and IdentityType=?  ", id,
				identityType).executeInt();
		String fileName = "";
//		boolean replaceFlag = false;
		if ("01".equals(identityType)) {
			FileUtil.mkdir(OSS_DOC + CrmPlugin.UPLOAD_PREFIX + "upload/people/identification/");
			fileName = "upload/people/identification/";
		} else if ("02".equals(identityType)) {
			FileUtil.mkdir(OSS_DOC + CrmPlugin.UPLOAD_PREFIX + "upload/customer/positionalTitle/");
			fileName = "upload/customer/positionalTitle/";
		} else if ("03".equals(identityType)) {
			FileUtil.mkdir(OSS_DOC + CrmPlugin.UPLOAD_PREFIX + "upload/customer/expert/certification/");
			fileName = "upload/customer/expert/certification/";
		} else if ("04".equals(identityType)) {
			FileUtil.mkdir(OSS_DOC + CrmPlugin.UPLOAD_PREFIX + "upload/customer/company/businessLicense/");
			fileName = "upload/customer/company/businessLicense/";
		} else if ("05".equals(identityType)) {
			FileUtil.mkdir(OSS_DOC + CrmPlugin.UPLOAD_PREFIX + "upload/customer/company/certification/");
			fileName = "upload/customer/company/certification/";
		} else {
			f("证书类型上传有误！");
			return;
		}
		Transaction trans = new Transaction();
		fileName = fileName + UUID.randomUUID().toString().replace("-", "") + "." + FileUtil.getExtension(fi.getName());
		if (version > lastVersion) {
			f("版本号传输有误！");
			return;
		}
		if (version == 0) {
			version = lastVersion + 1;
			certification.setValue(this.Request);
			certification.setVersion(version);
			if ("Cover".equals(coverOrBack)) {
				certification.setCoverFilePath(fileName);
			} else if ("Back".equals(coverOrBack)) {
				certification.setBackFilePath(fileName);
			} else {
				f("CoverOrBack 参数上传错误！");
				return;
			}
			certification.setVerified(1);// 状态 0表示未审核 1表示审核通过
			certification.setBelongCustomerID(id);
			certification.setID(NoUtil.getMaxID("CrmCertificationID"));
			certification.setAddTime(new Date());
			certification.setAddUser(Member.getUID());
			trans.insert(certification);
		} else {
			DataTable cerSet = new Q(
					" select * from crm_certification where BelongCustomerId=? and IdentityType=? and Version=?", id,
					identityType, version).fetch();
			certification.setValue(cerSet.get(0));
			certification.setValue(this.Request);
			// 图片写入操作
			if ("Cover".equals(coverOrBack)) {
				certification.setCoverFilePath(fileName);
			} else if ("Back".equals(coverOrBack)) {
				certification.setBackFilePath(fileName);
			} else {
				f("CoverOrBack 参数上传错误！");
				return;
			}
			certification.setVerified(1); // 状态 0表示未审核 1表示审核通过
			certification.setModifyTime(new Date());
			certification.setModifyUser(Member.getUID());
			trans.update(certification);
		}

		if (trans.commit()) {
			try {
				// 成功后才写入图片
				fi.write(new File(OSS_DOC + CrmPlugin.UPLOAD_PREFIX + fileName));
				$S("Url", AliyunOSSBL.generatePresignedUrl(OSSBucket.DOC, CrmPlugin.UPLOAD_PREFIX + fileName)
						.replace("https", "http"));
				$S("Version", certification.getVersion());
			} catch (Exception e) {
				f(Lang.get("Common.ExecuteFailed"));
				e.printStackTrace();
			}
		} else {
			f(Lang.get("Common.ExecuteFailed"));
		}
	}

	@Priv(loginType = LoginType.Member)
	public void initCompanyCertificate() {
		DataTable certification04 = new Q(
				"select * from crm_certification where BelongCustomerID=? and IdentityType = '04' order by Version desc limit 1",
				Member.getCompany()).fetch();
		DataTable certification05 = new Q(
				"select * from crm_certification where BelongCustomerID=? and IdentityType = '05' order by Version desc limit 1",
				Member.getCompany()).fetch();
//		EntLicensePath  企业营业执照    TestLicensePath  是机构资质证书
		if (certification04.getRowCount() != 0) {
			CrmCertification certification = new CrmCertification();
			for (DataRow dataRow : certification04) {
				certification.setValue(dataRow);
				certification.setCoverFilePath(AliyunOSSBL
						.generatePresignedUrl(OSSBucket.DOC, CrmPlugin.UPLOAD_PREFIX + certification.getCoverFilePath())
						.replace("https", "http"));
			}
			this.Response.put("data04", certification);
		}
		CrmCertification entity = new CrmCertification();
		if (certification05.getRowCount() != 0) {
			for (DataRow dataRow : certification05) {
				entity.setValue(dataRow);
				entity.setCoverFilePath(AliyunOSSBL
						.generatePresignedUrl(OSSBucket.DOC, CrmPlugin.UPLOAD_PREFIX + entity.getCoverFilePath())
						.replace("https", "http"));
			}
			this.Response.put("data05", entity);
		}
	}
}